// Copyright (C) 2024 Kumo inc.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
//

#include <kllm/openai/error.h>
#include <turbo/log/logging.h>
#include <kllm/utility/embedding.h>

namespace kllm {

    nlohmann::ordered_json format_aoi_error_response(const KaiResponse &response) {
        auto type = response.status().code();
        auto message = response.status().has_errmsg() ? response.status().errmsg() : "";
        return format_aoi_error_response(message, static_cast<ErrorType>(type));
    }

    nlohmann::ordered_json format_aoi_error_response(const turbo::Status &response) {
        return format_aoi_error_response(response.to_string(), ERROR_TYPE_INVALID_REQUEST);
    }

    nlohmann::ordered_json format_aoi_ok_response(const std::string& message) {
        return nlohmann::ordered_json {
                {"code",    0},
                {"message", message},
                {"type",    "ok"},
        };
    }

    nlohmann::ordered_json format_aoi_error_response(const std::string &message, ErrorType type) {
        std::string type_str;
        int code = 500;
        switch (type) {
            case ERROR_TYPE_INVALID_REQUEST:
                type_str = "invalid_request_error";
                code = 400;
                break;
            case ERROR_TYPE_AUTHENTICATION:
                type_str = "authentication_error";
                code = 401;
                break;
            case ERROR_TYPE_NOT_FOUND:
                type_str = "not_found_error";
                code = 404;
                break;
            case ERROR_TYPE_SERVER:
                type_str = "server_error";
                code = 500;
                break;
            case ERROR_TYPE_PERMISSION:
                type_str = "permission_error";
                code = 403;
                break;
            case ERROR_TYPE_NOT_SUPPORTED:
                type_str = "not_supported_error";
                code = 501;
                break;
            case ERROR_TYPE_UNAVAILABLE:
                type_str = "unavailable_error";
                code = 503;
                break;
        }
        return nlohmann::ordered_json {
                {"code",    code},
                {"message", message},
                {"type",    type_str},
        };
    }
}  // namespace kllm
